/**
 * @Name:  HighLightJs
 * @Author:
 * @Desc:  高亮代码
 * @Date: 2020-11-19 15:47:38
 */

import React, { Component } from "react";
import hljs from "highlight.js";
import { randomNum } from "@/utils";

import "highlight.js/styles/vs2015.css";
import styles from "./styles.module.less";

class HighLightJs extends Component {
  static defaultProps = {
    data: "", //代码
    type: "JavaScript" //代码类型，默认javascript,不区分大小写
  };
  componentDidMount() {
    this.code();
  }
  componentDidUpdate() {
    this.code();
  }
  /**
   * @name code
   * @description 监听返回data为true 启用
   */
  code = () => {
    const { data } = this.props;
    if (data) {
      document.querySelectorAll("pre code").forEach((block) => {
        hljs.highlightBlock(block);
      });
    }
  };
  /**
   * @name copy
   * @description 复制功能
   */
  copy = (id) => {
    let text = document.getElementById(`${id}`).innerText;
    let area = document.getElementById("area");
    area.value = text; // 修改文本框的内容
    area.select(); // 选择对象
    document.execCommand("Copy");
  };
  render() {
    const { type, data } = this.props;
    const id = randomNum(6);
    return (
      <div className={styles.content}>
        <pre>
          <code className={type} id={id}>
            {data}
          </code>
        </pre>
        <span onClick={() => this.copy(id)} className={styles.copy_btn} title="复制代码">
          &#9997;
        </span>
        {/**textarea:可以使文本保持原格式 */}
        <textarea id="area" className={styles.area} />
      </div>
    );
  }
}

export default HighLightJs;
